package com.kingtone.rongji.fragment;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import cn.trinea.android.view.autoscrollviewpager.AutoScrollViewPager;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.kingtone.rongji.BrowserActivity;
import com.kingtone.rongji.CartActivity;
import com.kingtone.rongji.HuoDongActivity;
import com.kingtone.rongji.LoginActivity;
import com.kingtone.rongji.MainActivity;
import com.kingtone.rongji.OrderListActivity;
import com.kingtone.rongji.ProductDetailActivity;
import com.kingtone.rongji.R;
import com.kingtone.rongji.TuiJianActivity;
import com.kingtone.rongji.YuShouActivity;
import com.kingtone.rongji.adapter.ImagePagerAdapter;
import com.kingtone.rongji.adapter.ImagePagerAdapter.OnImagePageClick;
import com.kingtone.rongji.biz.HomeImage;
import com.kingtone.rongji.tool.AppContasts;
import com.kingtone.rongji.tool.ListUtils;
import com.kingtone.rongji.tool.RongJiRestClient;
import com.kingtone.rongji.tool.RongJiUtils;
import com.kingtone.rongji.tool.SharedPreferencesUtil;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

public class DashboardFragment extends BaseFragment implements OnClickListener,OnImagePageClick {
	private String tag = "DashboardFragment";
	
	private static final int MAX_PIC_COUNT = 22;// 总共图片数
	private int currentPic = 0;
	
	private AutoScrollViewPager viewPager;
	private LinearLayout 		dotsView;
	private List<HomeImage>     imageList;
	private List<ImageView>     dotsItemView;
	
	private List<ImageView>     homeViewList;
	
    private DisplayImageOptions mOptions;
	
    public DashboardFragment() {
    	mOptions = new DisplayImageOptions.Builder().cacheInMemory(true).cacheOnDisk(true)
				.bitmapConfig(Bitmap.Config.RGB_565).delayBeforeLoading(100).build();
    }
    
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		Log.i(tag, "onCreateView");
		View view = initView(inflater);
		getAllHomeData();
		return view;
	}
	
	
	@Override
	public void onResume() {
		Log.i(tag, "onResume");
		super.onResume();
		
		// start auto scroll when onResume
        viewPager.startAutoScroll();
	}
	
	@Override
	public void onPause() {
		Log.i(tag, "onPause");
		super.onPause();
		
		// stop auto scroll when onPause
        viewPager.stopAutoScroll();
	}
	
	private View initView(LayoutInflater inflater) {
		View view = inflater.inflate(R.layout.fragment_dashboard, null);
		
		viewPager = (AutoScrollViewPager) view.findViewById(R.id.view_pager);
		dotsView  = (LinearLayout) view.findViewById(R.id.dots);
		
		// 初始化4张默认图片
		imageList = new ArrayList<HomeImage>();
		HomeImage item = new HomeImage();
		item.setDefaultImage(R.drawable.product_loading_img);
		imageList.add(item);
		
		ImagePagerAdapter adapter = new ImagePagerAdapter(this.mActivity, imageList).setInfiniteLoop(true);
		viewPager.setAdapter(adapter);
        viewPager.setOnPageChangeListener(new MyOnPageChangeListener());
        adapter.setOnImagePageClickListener(this);
        
        viewPager.setInterval(3000);
        viewPager.setAutoScrollDurationFactor(8.0);
        viewPager.startAutoScroll();
        viewPager.setCurrentItem(Integer.MAX_VALUE / 2 - Integer.MAX_VALUE / 2 % ListUtils.getSize(imageList));
        
        // Init dots
        refreshDots();
        
		view.findViewById(R.id.tuijian).setOnClickListener(this);
		view.findViewById(R.id.yushou).setOnClickListener(this);
		view.findViewById(R.id.huodong).setOnClickListener(this);
		view.findViewById(R.id.orders).setOnClickListener(this);
		
		addHomeImageListener(view);
		
		return view;
	}
	
	private void refreshDots() {
        dotsItemView = new ArrayList<ImageView>(imageList.size());
        dotsView.removeAllViews();
        ImageView dotItem;
        for(int i=0;i<imageList.size();i++) {
        	dotItem = new ImageView(this.mActivity);
        	dotItem.setImageResource(R.drawable.dot);
        	dotsItemView.add(dotItem);
        	dotsView.addView(dotItem);
        }
		setCurrentDotItem(0);
	}


	private void addHomeImageListener(View view) {
		if(null!=view) {
			homeViewList = new ArrayList<ImageView>();
			
			// G1
			ImageView item = (ImageView) view.findViewById(R.id.img_g1_0);
			item.setOnClickListener(this);
			homeViewList.add(item);
			
			item = (ImageView) view.findViewById(R.id.img_g1_1);
			item.setOnClickListener(this);
			homeViewList.add(item);
			
			item = (ImageView) view.findViewById(R.id.img_g1_2);
			item.setOnClickListener(this);
			homeViewList.add(item);
			
			item = (ImageView) view.findViewById(R.id.img_g1_3);
			item.setOnClickListener(this);
			homeViewList.add(item);
			
			item = (ImageView) view.findViewById(R.id.img_g1_4);
			item.setOnClickListener(this);
			homeViewList.add(item);
			
			// G2
			item = (ImageView) view.findViewById(R.id.img_g2_0);
			item.setOnClickListener(this);
			homeViewList.add(item);
			
			item = (ImageView) view.findViewById(R.id.img_g2_1);
			item.setOnClickListener(this);
			homeViewList.add(item);
			
			item = (ImageView) view.findViewById(R.id.img_g2_2);
			item.setOnClickListener(this);
			homeViewList.add(item);
			
			item = (ImageView) view.findViewById(R.id.img_g2_3);
			item.setOnClickListener(this);
			homeViewList.add(item);
			
			item = (ImageView) view.findViewById(R.id.img_g2_4);
			item.setOnClickListener(this);
			homeViewList.add(item);
			
			item = (ImageView) view.findViewById(R.id.img_g2_5);
			item.setOnClickListener(this);
			homeViewList.add(item);

			// G3
			item = (ImageView) view.findViewById(R.id.img_g3_0);
			item.setOnClickListener(this);
			homeViewList.add(item);
			
			item = (ImageView) view.findViewById(R.id.img_g3_1);
			item.setOnClickListener(this);
			homeViewList.add(item);
			
			item = (ImageView) view.findViewById(R.id.img_g3_2);
			item.setOnClickListener(this);
			homeViewList.add(item);
			
			// G4
			item = (ImageView) view.findViewById(R.id.img_g4_0);
			item.setOnClickListener(this);
			homeViewList.add(item);
			
			item = (ImageView) view.findViewById(R.id.img_g4_1);
			item.setOnClickListener(this);
			homeViewList.add(item);
			
			item = (ImageView) view.findViewById(R.id.img_g4_2);
			item.setOnClickListener(this);
			homeViewList.add(item);
			
			item = (ImageView) view.findViewById(R.id.img_g4_3);
			item.setOnClickListener(this);
			homeViewList.add(item);
			
			item = (ImageView) view.findViewById(R.id.img_g4_4);
			item.setOnClickListener(this);
			homeViewList.add(item);
			
			item = (ImageView) view.findViewById(R.id.img_g4_5);
			item.setOnClickListener(this);
			homeViewList.add(item);
			
			item = (ImageView) view.findViewById(R.id.img_g4_6);
			item.setOnClickListener(this);
			homeViewList.add(item);
		}
	}
	
	/*private int getDefaultImageResource(int index) {
		int res = 0;
		switch (index) {
		//G1
		case 2:
			res = R.drawable.g1_default0;
			break;
		case 3:
			res = R.drawable.g1_default1;
			break;
		case 4:
			res = R.drawable.g1_default2;
			break;
		case 5:
			res = R.drawable.g1_default3;
			break;
		case 6:
			res = R.drawable.g1_default4;
			break;
		
	    //G2
		case 7:
			res = R.drawable.g2_default0;
			break;
		case 8:
			res = R.drawable.g2_default1;
			break;
		case 9:
			res = R.drawable.g2_default2;
			break;
		case 10:
			res = R.drawable.g2_default3;
			break;
		case 11:
			res = R.drawable.g2_default4;
			break;
		case 12:
			res = R.drawable.g2_default5;
			break;
			
		//G3
		case 13:
			res = R.drawable.g3_default0;
			break;
		case 14:
			res = R.drawable.g3_default1;
			break;
		case 15:
			res = R.drawable.g3_default2;
			break;
		
		//G4
		case 16:
			res = R.drawable.g4_default0;
			break;
		case 17:
			res = R.drawable.g4_default1;
			break;
		case 18:
			res = R.drawable.g4_default2;
			break;
		case 19:
			res = R.drawable.g4_default3;
			break;
		case 20:
			res = R.drawable.g4_default4;
			break;
		case 21:
			res = R.drawable.g4_default5;
			break;
		case 22:
			res = R.drawable.g4_default6;
			break;
		default:
			break;
		}
		return res;
	}*/


	private void setCurrentDotItem(int index) {
		if(null == dotsItemView) {
			return;
		}
		
		if(index>-1 && index<dotsItemView.size()) {
			for(int i=0;i<dotsItemView.size();i++) {
				if(index==i) {
					dotsItemView.get(i).setImageResource(R.drawable.dot_pressed);
				} else {
					dotsItemView.get(i).setImageResource(R.drawable.dot);
				}
			}
		}
	}
	
	// 首页总共22个区域需要获取图片，请求服务器22次
	private void getAllHomeData() {
		currentPic++;
		
		String code = "-999";
		String themes = "default";
		String name = "Mobile_NewTop";
		if(currentPic<10) {
			name += "0" + currentPic;
		} else {
			name += currentPic;
		}
		
		RongJiRestClient.getHomePics(name, code, themes, new AsyncHttpResponseHandler() {
			
			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				if(arg0==200) {
					String responseText = new String(arg2);
					Log.d(tag, "Result [" + currentPic + "]:" + responseText);
					
					Gson gson = new Gson();
					JsonParser parser = new JsonParser();
					try
					{
						JsonArray array = parser.parse(responseText).getAsJsonArray();
						List<HomeImage> list = new ArrayList<HomeImage>();
						for(JsonElement obj:array) {
							HomeImage object = gson.fromJson(obj, HomeImage.class);
							
							// 忽略微信打开项目
//							if(RongJiUtils.getActionType(object)==RongJiUtils.ACTION_OPEN_WEXIN) {
//								continue;
//							}
							
							RongJiUtils.handleHomeImageUrl(object);
							list.add(object);
						}
						showImage(currentPic, list);
					}
					catch(Exception e)
					{
						e.printStackTrace();
					}
				} else {
					Log.e(tag, "Error:code=" + arg0);
				}
				
				/*if(currentPic>1) {
					// Test data
					HomeImage item = new HomeImage();
					View itemView = homeViewList.get(currentPic-2);
					if(currentPic==3 || currentPic==4 || currentPic==5 || currentPic==13 || currentPic==14 || currentPic==15) {// 搜索类型
						item.setNavigateUrl("0");
					} else if(currentPic==6 || currentPic==16 || currentPic==22) {// 专题
						item.setNavigateUrl("1");
					} else {// 产品详情
						item.setNavigateUrl("2");
					}
					itemView.setTag(item);
				}*/
				
				if(currentPic==MAX_PIC_COUNT) {
					currentPic = 0;
				} else {
					getAllHomeData();
				}
			}
			
			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
				Log.e(tag, "Failed:code=" + arg0);
				if(null != arg3) {
					arg3.printStackTrace();
				}
			}
		});
	}
	
	private void showImage(int currentPic, List<HomeImage> list) {
		if(currentPic==1) {
			imageList.clear();
			imageList.addAll(list);
			ImagePagerAdapter adapter = new ImagePagerAdapter(this.mActivity, imageList).setInfiniteLoop(true);
			viewPager.setAdapter(adapter);
			adapter.setOnImagePageClickListener(this);
			
			refreshDots();
		} else if (currentPic >= 2) {
			HomeImage item = list.get(0);// 除滚动页面，其他都是单张图片
			ImageView itemView = homeViewList.get(currentPic - 2);
			if (null != item && null != itemView) {
				itemView.setTag(item);
				if (!TextUtils.isEmpty(item.getImageUrl())
						&& item.getImageUrl().startsWith("http")) {
					itemView.setScaleType(ScaleType.FIT_XY);
					ImageLoader.getInstance().displayImage(item.getImageUrl(),
							itemView, mOptions);
				} else {
					// itemView.setImageResource(getDefaultImageResource(currentPic));
				}
			}
		}
	}
	
	public class MyOnPageChangeListener implements OnPageChangeListener {

        @Override
        public void onPageSelected(int position) {
        	setCurrentDotItem((position) % ListUtils.getSize(imageList));
        }

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}

        @Override
        public void onPageScrollStateChanged(int arg0) {}
    }

	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
		case R.id.tuijian:
			startActivity(new Intent(this.mActivity, TuiJianActivity.class));
			break;
		case R.id.yushou:
			startActivity(new Intent(this.mActivity, YuShouActivity.class));
			break;
		case R.id.huodong:
			startActivity(new Intent(this.mActivity, HuoDongActivity.class));
			break;
		case R.id.orders:
			if (!SharedPreferencesUtil.getInstance(this.mActivity).getBoolean(
					AppContasts.IS_LOGINED_KEY)) {
				Intent intent = new Intent(this.mActivity, LoginActivity.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(intent);
			} else {
				Intent intent = new Intent(this.mActivity, OrderListActivity.class);
				intent.putExtra("flag", AppContasts.ORDER_STATUS_WAITING_PAY);
				startActivity(intent);
				this.mActivity.setCurrentTab("Profile", null);
			}
			break;
		default:
			HomeImage item = (HomeImage) arg0.getTag();
			if(null!=item) {
				goImageAction(item);
			}
			break;
		}
	}


	@Override
	public void onImagePageClick(int index) {
		HomeImage item = imageList.get(index);
		if(null!=item) {
			goImageAction(item);
		}
	}
	
	private void goImageAction(HomeImage item) {
		if(null != item) {
			
			int type = RongJiUtils.getActionType(item);
			switch (type) {
			case RongJiUtils.ACTION_PRODACTION:
				String pid = RongJiUtils.getProductIdFromHomeImage(item);
				if(!TextUtils.isEmpty(pid)) {
					RongJiUtils.goProductDetail(getActivity(), pid);
				}
				break;
			case RongJiUtils.ACTION_SEARCH:
				String key = RongJiUtils.getSearchKeyFromHomeImage(item);
				if(!TextUtils.isEmpty(key)) {
					RongJiUtils.goSearch(getActivity(), key);
				}
				break;
			case RongJiUtils.ACTION_TOPIC:
				String navUrl = item.getNavigateUrl().concat("?mode=1");
				Intent intent = new Intent(getActivity(), BrowserActivity.class);
				intent.putExtra("NavUrl", navUrl);
				startActivity(intent);
				break;
			case RongJiUtils.ACTION_WEXIN:
				String url = item.getNavigateUrl();
				RongJiUtils.goHuodong(getActivity(), url.concat("?mode=1"));
				break;
			case RongJiUtils.ACTION_CATEGORY:
				String sid = RongJiUtils.getCategoryIdFromHomeImage(item);
				if(!TextUtils.isEmpty(sid)) {
					RongJiUtils.goSearch(getActivity(), Integer.parseInt(sid));
				}
				break;
			case RongJiUtils.ACTION_OPEN_WEXIN:
				// 暂不处理
				break;
			case RongJiUtils.ACTION_ADV:
				String navUrl2 = item.getNavigateUrl().concat("?from=home");
				Intent intent2 = new Intent(getActivity(), BrowserActivity.class);
				intent2.putExtra("NavUrl", navUrl2);
				startActivity(intent2);
				break;
			default:
				break;
			}
		}
	}
}
